package com.ln.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.ln.yygh.cmn.client.DictFeignClient;
import com.ln.yygh.hosp.mapper.HospitalSetMapper;
import com.ln.yygh.hosp.repository.HospitalRepository;
import com.ln.yygh.hosp.service.HospitalSetService;
import com.ln.yygh.hosp.service.*;
import com.ln.yygh.hosp.util.MD5;
import com.ln.yygh.model.hosp.*;
import com.ln.yygh.vo.hosp.*;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author: lianXiaoChen
 * @create: 2021-05-29 14:21
 */
@Service
public class HospitalerviceImpl implements Hospitalervice {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Resource
    private HospitalSetMapper hospitalSetMapper;
    @Resource
    private DictFeignClient dictFeignClient;

    //修改-添加
    @Override
    public void saveHospital(Map<String, Object> paramMap) {
        /**
         * 先把map转成json，再把json转成实体类
         */
        String json = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(json, Hospital.class);
        /**
         * 保存和修改是一起的
         * 需要我们进行判断，要是有就是修改，没有就是新增
         * 医院编码是唯一的，使用这个试题里面的医院的编码去数据库查询，看看有没有信息
         *
         */
        if (hospital != null) {

            Hospital hp = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
            /**
             * 有的话，走修改，么有的话就是新增
             */
            if (hp == null) {
                /**
                 * //0：未上线 1：已上线
                 */
                hospital.setStatus(0);
                hospital.setCreateTime(new Date());
                hospital.setUpdateTime(new Date());
                hospital.setIsDeleted(0);
                hospitalRepository.save(hospital);
            } else {
                /**
                 * 因为我们修改的时候，要把id存进去
                 * 我们按照医院编码去查询的数据
                 */
                hospital.setId(hp.getId());
                hospital.setStatus(hp.getStatus());
                hospital.setCreateTime(hp.getCreateTime());
                hospital.setUpdateTime(new Date());
                hospital.setIsDeleted(0);
                hospitalRepository.save(hospital);
            }
        }
    }

    //鉴权
    @Override
    public boolean getSign(Map<String, Object> paramMap) {
        String hsocode = (String) paramMap.get("hoscode");
        String sign = (String) paramMap.get("sign");
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hoscode", hsocode);
        HospitalSet hospitalSet = hospitalSetMapper.selectOne(queryWrapper);
        if (hospitalSet != null) {
            /**
             * 密码数据库密码进行加密·
             */
            String encrypt = MD5.encrypt(hospitalSet.getSignKey());
            if (sign != null && sign.equals(encrypt)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Hospital getHospitalByHoscode(String hoscode) {//根据id查询
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    @Override//(分页+模糊)医院列表
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //创建Pageable对象
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        //创建条件构造器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//模糊 （改变字符串类型）
                .withIgnoreCase(true);//忽略大小写
        //吧传送来的vo对象转化为Hospital对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
        //创建Example实例查询
        Example<Hospital> example = Example.of(hospital, matcher);
        //调用方法查询操作
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        //获取查询的list，遍历并且进行医院等级封装
        pages.getContent().stream().forEach(item -> {
            this.setHospitalHosType(item);
        });
        return pages;
    }

    @Override//上线下线功能
    public void updateStatus(String id, Integer status) {
            //根据id查询医院 信息
            Hospital hospital = hospitalRepository.findById(id).get();
            //设置修改的值
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
    }

    @Override//根据id查询
    public Map<String, Object> selectHospById(String id) {
        //医院等级信息以及医院详情信息
        Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
        HashMap<String, Object> map = new HashMap<>();
        //医院基本信息（包含医院等级  详细地址）
        map.put("hospital",hospital);
        //单独处理 直观一点
        map.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return map;
    }

    @Override//根据医院名称查询
    public String getHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital != null){
            return hospital.getHosname();
        }
            return null;
    }

    private Hospital setHospitalHosType(Hospital hospital) {
        //根据dictCode和value获取医院等级名称
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        String provinceName = dictFeignClient.getName(hospital.getProvinceCode());
        String cityName = dictFeignClient.getName(hospital.getCityCode());
        String districtName = dictFeignClient.getName(hospital.getDistrictCode());
        //查询省市区
        hospital.getParam().put("districtString", hostypeString);
        hospital.getParam().put("finallAddress", provinceName + cityName + districtName);

        return hospital;
    }



    @Override
    public List<Hospital> findByHosName(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        HashMap<String, Object> map = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHosType(this.getHospitalByHoscode(hoscode));
        map.put("hospital",hospital);
        //预约规则
        map.put("bookingRule",hospital.getBookingRule());
        //不重复返回
        hospital.setBookingRule(null);
        return map;
    }

}
